/*
 * @Author: xiaoyan
 * @Date: 2021-09-22 17:11:37
 * @LastEditors: xiaoyan
 * @LastEditTime: 2021-09-29 16:02:16
 * @Description: axios-mapper 请求
 * @FilePath: \vue3-ts-demo\src\utils\https.ts
 */
import { getToken,removeToken } from '@/utils/cookies'
import HttpClient, { HttpClientConfig } from 'axios-mapper'
import { ElMessage } from 'element-plus'
import router from '@/router'
import {useStore}  from '@/store'

const config: HttpClientConfig = {
    baseURL:"",
    timeout:50000,
    headers: {
        auth: ""
    }
}

const https = new HttpClient(config);

https.httpClient.interceptors.request.use(config=>{
    if(useStore().state.user.token){
        config.headers['auth'] = getToken()
    }
    return config;
},error=>{
    return Promise.reject(error);
});

https.httpClient.interceptors.response.use(response=>{
    return response;
},error=>{
    if(error.response){
        switch (error.response.status) {
          case 401:
          case 403: {
            removeToken();
            router.push({
              path: "/login"
            });
            break;
          }
        }
      }else{
        ElMessage({
          message: errTip(error.message),
          type: 'error',
          duration: 5 * 1000
        })
      }
    return Promise.reject(error);
});

function errTip(msg:string){
    if(msg.indexOf("timeout") != -1){
        return "请求超时！";
    }else if(msg.indexOf("Network Error") != -1){
        return "无法连接网络！";
    }else{
        return msg;
    }
}

export default https
